package com.shoulder.boot.system.utils;

import com.shoulder.boot.system.entity.Tenant;
import com.shoulder.boot.system.mapper.TenantMapper;
import com.shoulder.boot.system.vo.LogVo;
import com.shoulder.core.utils.FuncUtils;
import com.shoulder.core.utils.MapUtils;
import com.shoulder.log.Log;
import com.shoulder.mybatis.utils.PageUtils;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
public class LogUtils implements PageUtils<Log, LogVo> {

    //(租户id,租户对象)
    private Map<String, Tenant> tenantMap;

    public static LogUtils buildUtils(List<Log> records, TenantMapper tenantMapper) {
        LogUtils logUtils = new LogUtils();
        List<String> tenantIds = FuncUtils.toList(records, Log::getTenantId);
        if (!CollectionUtils.isEmpty(tenantIds) && tenantMapper != null) {
            logUtils.setTenantMap(tenantMapper.selectBatchIds(tenantIds).stream().collect(Collectors.toMap(Tenant::getId, t -> t)));
        }
        return logUtils;
    }

    @Override
    public LogVo toVo(Log log) {
        LogVo vo = new LogVo();
        BeanUtils.copyProperties(log, vo);
        vo.setTenantName(MapUtils.get(log.getTenantId(), tenantMap, new Tenant()).getName());
        return vo;
    }
}
